//
//  YDWithdrawalController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/13.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDWithdrawalController.h"
#import "YDRechargeTopView.h"
#import "YDRechargeTableCell.h"
#import "YDWithdrawalTableFooterView.h"
#import "YDRechargeTableHeaderView.h"
#import "YDRechargeWithdrawalButtonView.h"
#import "YDEditInformationController.h"//编辑支行信息
#import "YDBindBankCardController.h"//绑卡
#import "YDAdvertViewController.h"
#import "YDPaymentPasswordController.h"
#import "YDWithdrawalSuccessViewController.h"
#import "YDBankCardModel.h"
#import "YDPayAlertView.h"
#import "OttoKeyboardView.h" //自定义键盘

//static NSString * const WithdrawCash = @"/payment/withdrawals";

@interface YDWithdrawalController ()<UITextFieldDelegate , UITableViewDelegate , UITableViewDataSource , SYWithdrawalTableFooterViewDelegate , SYRechargeTableCellDelegate,SYRechargeWithdrawalButtonViewDelegate,TextFieldClickReturnDelegate>


//topView
@property (nonatomic , weak) YDRechargeTopView*topView;

//金额
@property (nonatomic , weak) UIView *accountContentView;
//金额label
@property (nonatomic , weak) UILabel *accountLabel;
//金额输入框
@property (nonatomic , weak) OttoTextField *accountTextField;

//tableView
@property (nonatomic , weak) UITableView *tableView;


//充值按钮
@property (nonatomic , weak) YDRechargeWithdrawalButtonView *buttonView;

//已绑卡数组
@property (nonatomic , strong) NSMutableArray *tiedCardArray;

//当前的选中银行模型
@property (nonatomic, strong)YDBankCardModel *currentBankModel;


@end

@implementation YDWithdrawalController

-(NSMutableArray *)tiedCardArray
{
    if (_tiedCardArray == nil) {
        _tiedCardArray = [NSMutableArray array];
    }
    return _tiedCardArray;
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"提现";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setHidden:YES];
    [self dismissKeyBoard];
    
    [self topView];
    
    //添加输入框
    [self addTextField];
    
    [self tableView];
    
    [self buttonView];
    
    [self setUpDataManger];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *accountString = [[SYUserDataManger sharedInstance] getUserAccountNumberString];
    self.topView.amountString = accountString;
    
    [self loadData];
}


#pragma mark -UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}


- (void)textFieldDidChange:(UITextField *)textField
{
    [self updateConfirmBtn];
   
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    if ([textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            return NO;
        }
    }
//只能输入一个小数点及小数点两位
    if ([string isEqualToString:@"."]) {
        if ([textField.text containsString:@"."]) {
            return NO;
        }else{
            return YES;
        }
    }
    
    if ([textField.text containsString:@"."]) {
        if (range.location > [textField.text rangeOfString:@"."].location + 2) {
            return NO;
        }
    }
    
    
    return YES;
}


-(void)updateConfirmBtn
{
    if (self.accountTextField.text.length && self.currentBankModel.isSelected) {
        [self.buttonView enableButton];
    }else
    {
         [self.buttonView disableButton];
    }
}

#pragma mark - 点击提现

- (void)rechargeWithdrawalButtonViewButtonClick
{

    
    if(![NSString isFloatNumString:self.accountTextField.text] || [self.accountTextField.text floatValue] <= 0)
    {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"请输入正确的金额" isExistNav:NO];
        return;
    }
//
    //不验证支行信息
//    if (!self.currentBankModel.branchName.length) {
//        [self goChargeAlert];
//        return;
//    }
    [self loadUserCardBindInfo];
   
    
}


- (void)withdrawSuccess
{
    
    YDWithdrawalSuccessViewController *vc = [[YDWithdrawalSuccessViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
- (void)pay
{

    //paymentType:1银联支付,2扫码支付
    NSDictionary *dic = @{@"amount"      : self.accountTextField.text,
                          @"bindCardId"  : @(self.currentBankModel.Id),
                          };

//
     NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    YDPayAlertView *payView = [[YDPayAlertView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, LKScreenH) inputFinish:^(NSString *passWord) {
        [params setObject:passWord forKey:@"paymentPassword"];
        
        [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
        
        [BaseNetRequest sessionRequestWithparameters:params method:POSTMethod requstType:WithdrawCash WithSuccessBlock:^(NSDictionary *resultDict) {
            
            
            [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
            
            if ([resultDict[@"code"] integerValue] == 200)
            {
                [self withdrawSuccess];
            }
            else
            {
                [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                              isExistNav:NO];
            }
            
        } failBlock:^(NSError *error) {
            [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:@"网络异常"
                                                          isExistNav:NO];
        }];

  
     }];
    [payView show];
}


#pragma mark - 获取是否绑卡信息
-(void)loadUserCardBindInfo
{
    
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetSettingInformationList WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];

        if ([resultDict[@"code"] integerValue] == 200) {
            
            BOOL isBindCard = [resultDict[@"result"][@"settingPaymentPassword"] boolValue];
            //是否设置支付密码
            if (!isBindCard) {
                [self goSetupPayPassword];
            }
            else
            {
                [self pay];
            }
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:NO];
        }
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:NO];
    }];
}

#pragma mark - 去设置支行信息alert
-(void)goChargeAlert
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"您还没有填写支行信息，请先填写支行信息" ButtonTitle:@"去填写" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
        YDEditInformationController *editBankVc = [[YDEditInformationController alloc] init];
        editBankVc.hidesBottomBarWhenPushed = YES;
        editBankVc.model = self.currentBankModel;
        [self.navigationController pushViewController:editBankVc animated:YES];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

#pragma mark - 去支付密码alert
-(void)goSetupPayPassword
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"您还没有设置支付密码，请先设置支付密码" ButtonTitle:@"去设置" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
        YDPaymentPasswordController *vc = [[YDPaymentPasswordController alloc] init];
        
        [self.navigationController pushViewController:vc animated:YES];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSArray *subviews = [self.view subviews];
    for (UITextField *textField in subviews) {
        if (textField == self.accountTextField) {
            [self.accountTextField resignFirstResponder];
        }
    }
    
}
#pragma mark - TextViewClickReturnDelegate
- (void)textViewClickReturn:(OttoTextView *)textView{
    [textView resignFirstResponder];
    NSLog(@"return - %@",textView.text);
}

#pragma mark - TextFieldClickReturnDelegate
- (void)textFieldClickReturn:(OttoTextField *)textField{
    [textField resignFirstResponder];
    NSLog(@"return - %@",textField.text);
}

////*******YDRechargeTopView********////
-(YDRechargeTopView *)topView
{
    if (_topView == nil) {
        NSString *accountString = [[SYUserDataManger sharedInstance] getUserAccountNumberString];
        YDRechargeTopView *topView = [YDRechargeTopView rechargeTopViewWithAmount:accountString];
        topView.title = @"提现";
        [self.view addSubview:topView];
        __weak typeof(self)weself = self;
        [topView setBackBlock:^(BOOL isSelected) {
            [weself.navigationController popViewControllerAnimated:YES];
        }];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            if (isPhoneX) {
                 make.height.equalTo(@(rateX812(170) + 24));
            }else{
                make.height.equalTo(@(rate750(170)));
            }
        }];
        _topView = topView;
    }
    return _topView;
}

//添加输入框
-(void)addTextField
{
    [self accountContentView];
    [self accountLabel];
    [self accountTextField];
}
///*********accountContentView*******///////
-(UIView *)accountContentView
{
    if (_accountContentView == nil) {
        UIView *accountContentView = [[UIView alloc] init];
        [self.view addSubview:accountContentView];
        accountContentView.backgroundColor = [UIColor whiteColor];
        accountContentView.userInteractionEnabled = YES;
        [accountContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            if (isPhoneX) {
                make.top.equalTo(self.topView.mas_bottom).offset(rateX812(10));
                make.height.equalTo(@(rateX812(50)));
            }else{
                make.top.equalTo(self.topView.mas_bottom).offset(rate750(10));
                make.height.equalTo(@(rate750(50)));
            }
        }];
        
        _accountContentView = accountContentView;
    }
    return _accountContentView;
}
//金额label
-(UILabel *)accountLabel
{
    if (_accountLabel == nil) {
        UILabel *accountLabel = [[UILabel alloc] init];
        [self.accountContentView addSubview:accountLabel];//104 114 132
        accountLabel.textColor = NumberColor(104, 114, 132);
        accountLabel.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        accountLabel.text = @"金额";
        accountLabel.textAlignment = NSTextAlignmentCenter;
        [accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.accountContentView);
            make.left.equalTo(self.accountContentView);
            make.width.equalTo(@(rate375(61)));
        }];
        _accountLabel = accountLabel;
    }
    return _accountLabel;
}
-(OttoTextField *)accountTextField
{
    if (_accountTextField == nil) {
        OttoTextField *accountTextField = [[OttoTextField alloc] init];
        [self.accountContentView addSubview:accountTextField];
        accountTextField.textColor = [UIColor blackColor];
        accountTextField.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        accountTextField.placeholder = @"请输入提现金额";
      
        [accountTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        accountTextField.backgroundColor = [UIColor clearColor];
        accountTextField.borderStyle = UITextBorderStyleNone;
        accountTextField.textAlignment = NSTextAlignmentLeft;
        accountTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        accountTextField.keyboardType = UIKeyboardTypeNumberPad;
        accountTextField.returnKeyType =UIReturnKeyDone;
        [accountTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        
        [accountTextField setKeyboardType:KeyboardTypeNumber];
        [accountTextField setNumberKeyboardType:NumberKeyboardTypeNumber];
        accountTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        accountTextField.textFieldClickReturnDelegate = self;

        [accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.accountContentView);
            make.left.equalTo(self.accountLabel.mas_right);
            make.right.equalTo(self.accountContentView.mas_right).offset(-rate375(16));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(20)));
            }else{
                make.height.equalTo(@(rate750(20)));
            }
        }];
        accountTextField.tintColor = [UIColor blackColor];
        accountTextField.delegate = self;

        _accountTextField = accountTextField;
    }
    return _accountTextField;
}
//tableView
-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        //        tableView.scrollEnabled = NO;
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(self.accountContentView.mas_bottom);

        }];
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}
/////********充值按钮*******///////
-(YDRechargeWithdrawalButtonView *)buttonView
{
    if (_buttonView == nil) {
        YDRechargeWithdrawalButtonView *buttonView = [YDRechargeWithdrawalButtonView rechargeWithdrawalButtonWithButtonTitle:@"提现"];
        [self.view addSubview:buttonView];
        buttonView.delegate = self;
        
        [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(63)));
            }else{
                make.height.equalTo(@(rate750(50)));
            }
        }];
        
        
        _buttonView = buttonView;
    }
    return _buttonView;
}

/////******加载数据**********////
-(void)setUpDataManger
{

    
    
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES ;
    //隐藏状态
    header.stateLabel.hidden = YES ;
    self.tableView.mj_header = header;
    
   
    //    [header beginRefreshing];//马上进入刷新
}
-(void)loadData
{
    
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:BindBankCardList WithSuccessBlock:^(NSDictionary *resultDict) {
        [self.tableView.mj_header endRefreshing];
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if ([resultDict[@"code"] integerValue] == 200) {
            self.tiedCardArray = [YDBankCardModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            
            if (self.tiedCardArray.count) {
                
                
                if (self.currentBankModel == nil) {
                    YDBankCardModel *obj = [self.tiedCardArray firstObject];
                    obj.isSelected = YES;
                    self.currentBankModel = obj;
                }else
                {
                    [self.tiedCardArray enumerateObjectsUsingBlock:^(YDBankCardModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //每次进来请求刷新数据选中model问题
                        if (self.currentBankModel && self.currentBankModel.Id == obj.Id) {
                            obj.isSelected = YES;
                            self.currentBankModel = obj;
                            *stop = YES;
                        }
                        
                    }];
                }
            }
           
            [self.tableView reloadData];
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:NO];
            
        }
    } failBlock:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:NO];
    }];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tiedCardArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(125) : rate750(125);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(38) : rate750(38);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(300) : rate750(300);
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YDRechargeTableHeaderView *headerView = [YDRechargeTableHeaderView headerViewWithTableView:tableView];
    return headerView;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    YDWithdrawalTableFooterView *footerView = [YDWithdrawalTableFooterView footerViewWithTableView:tableView];
    footerView.delegate = self;
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (int i = 0 ; i < self.tiedCardArray.count ; i ++) {
        YDBankCardModel *model = self.tiedCardArray[i];
        if (i != indexPath.row) {
            model.isSelected = NO;
        }else{
            model.isSelected = !model.isSelected;
            self.currentBankModel = model;
        }
        
    }
    
    [self updateConfirmBtn];
    [self.tableView reloadData];

}
#pragma PZWithdrawalTableFooterViewDelegate
-(void)withdrawalTableFooterViewDidClickAddButton:(YDWithdrawalTableFooterView *)footerView
{
    //    DDLog(@"添加银行卡")
    YDBindBankCardController *vc = [[YDBindBankCardController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDRechargeTableCell *cell = [YDRechargeTableCell cellWithTableView:tableView];
    cell.delegate = self;
    YDBankCardModel *model = self.tiedCardArray[indexPath.row];
    cell.model = model;
    cell.payStyle = Withdraw;
    return cell;
}



#pragma PZRechargeTableCellDelegate
-(void)rechargeTableCellDidSelected:(YDRechargeTableCell *)cell
{
    //获取信息，取反，刷新界面
    DDLog(@"点击了选择某一个银行")
    
   
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    
    
    for (int i = 0 ; i < self.tiedCardArray.count ; i ++) {
        YDBankCardModel *model = self.tiedCardArray[i];
        if (i != indexPath.row) {
            model.isSelected = NO;
        }else{
            model.isSelected = !model.isSelected;
            self.currentBankModel = model;
        }
       
    }
    
    [self updateConfirmBtn];
    [self.tableView reloadData];

}
//编辑支行信息
-(void)rechargeTableCellDidClickChangeBankInformation:(YDRechargeTableCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YDBankCardModel *model = self.tiedCardArray[indexPath.row];
    YDEditInformationController *vc = [[YDEditInformationController alloc] init];
    vc.model = model;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


@end
